<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>地图导航 - 多语言旅行助手</title>
    <link rel="stylesheet" href="style.css">
    <!-- 引入高德地图 API -->
    <link rel="stylesheet" href="https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css" />
    <script src="https://webapi.amap.com/maps?v=2.0&key=YOUR_AMAP_KEY"></script>
</head>
<body>
    <!-- 顶部导航栏 -->
    <header>
        <h1>多语言旅行助手</h1>
        <nav>
            <ul>
                <li><a href="index.html">首页</a></li>
                <li><a href="learning.html">学习中心</a></li>
                <li><a href="translation.html">翻译</a></li>
                <li><a href="culture.html">文化知识库</a></li>
                <li><a href="map.html" class="active">离线地图</a></li>
                <li><a href="travel-plan.html">旅行计划</a></li>
                <li><a href="offline-content.html">离线内容</a></li>
                <li><a href="profile.html">个人资料</a></li>
                <li><a href="settings.html">设置</a></li>
            </ul>
        </nav>
    </header>

    <!-- 侧边导航栏 -->
    <aside class="side-nav">
        <ul>
            <li>
                <a href="index.html">
                    <img src="images/home.svg" alt="首页图标">
                    <span>首页</span>
                </a>
            </li>
            <li>
                <a href="learning.html">
                    <img src="images/book-open-bold.svg" alt="学习图标">
                    <span>学习</span>
                </a>
            </li>
            <li>
                <a href="translation.html">
                    <img src="images/vector_25_310.svg" alt="翻译图标">
                    <span>翻译</span>
                </a>
            </li>
            <li>
                <a href="culture.html">
                    <img src="images/globe-bold.svg" alt="文化图标">
                    <span>文化</span>
                </a>
            </li>
            <li>
                <a href="map.html" class="active">
                    <img src="images/vector_25_317.svg" alt="地图图标">
                    <span>地图</span>
                </a>
            </li>
            <li>
                <a href="offline-content.html">
                    <img src="images/vector_25_324.svg" alt="离线内容图标">
                    <span>离线</span>
                </a>
            </li>
            <li>
                <a href="settings.html">
                    <img src="images/vector_25_331.svg" alt="设置图标">
                    <span>设置</span>
                </a>
            </li>
        </ul>
    </aside>

    <!-- 内容区 -->
    <main class="content map-content">
        <h1 class="page-title">智能导航</h1>
        
        <div class="map-container">
            <div class="map-sidebar">
                <div class="map-search">
                    <input type="text" id="map-search-input" placeholder="搜索地点、景点或地址">
                    <button id="map-search-btn" class="primary-btn">
                        <img src="images/placeholder.svg" alt="搜索" width="16" height="16">
                        搜索
                    </button>
                </div>
                
                <div class="map-filters">
                    <h3>兴趣点筛选</h3>
                    <div class="filter-options">
                        <label class="filter-option">
                            <input type="checkbox" value="tourist" checked>
                            <span>旅游景点</span>
                        </label>
                        <label class="filter-option">
                            <input type="checkbox" value="historical">
                            <span>历史遗迹</span>
                        </label>
                        <label class="filter-option">
                            <input type="checkbox" value="museum">
                            <span>博物馆</span>
                        </label>
                        <label class="filter-option">
                            <input type="checkbox" value="restaurant">
                            <span>餐厅</span>
                        </label>
                        <label class="filter-option">
                            <input type="checkbox" value="hotel">
                            <span>酒店</span>
                        </label>
                    </div>
                </div>
                
                <div class="nearby-places">
                    <h3>附近历史文化景点</h3>
                    <div id="nearby-list" class="nearby-list">
                        <div class="loading">加载中...</div>
                    </div>
                </div>
            </div>
            
            <div id="map-container" class="map-view"></div>
            
            <div id="place-info" class="place-info">
                <div class="place-header">
                    <h2 id="place-name">选择一个地点查看详情</h2>
                    <button id="close-info" class="close-btn">×</button>
                </div>
                <div id="place-content" class="place-content">
                    <p>点击地图上的标记或从左侧列表选择一个地点，查看详细信息。</p>
                </div>
                <div class="place-actions">
                    <button id="navigate-btn" class="primary-btn">
                        <img src="images/placeholder.svg" alt="导航" width="16" height="16">
                        导航到这里
                    </button>
                    <button id="translate-info-btn" class="secondary-btn">
                        <img src="images/placeholder.svg" alt="翻译" width="16" height="16">
                        翻译信息
                    </button>
                </div>
            </div>
        </div>
    </main>

    <footer>
        <p>&copy; 2025 多语言旅行助手 | 版本 1.0</p>
    </footer>

    <script src="script.js"></script>
    <script>
        // 地图功能
        document.addEventListener('DOMContentLoaded', function() {
            // 从环境变量或配置中获取API密钥
            const getApiKey = async () => {
                try {
                    const response = await fetch('/api/config');
                    const data = await response.json();
                    return data.amapKey;
                } catch (error) {
                    console.error('获取API密钥失败:', error);
                    return 'YOUR_AMAP_KEY'; // 默认值，应替换为实际密钥
                }
            };
            
            // 初始化地图
            const initMap = () => {
                // 创建地图实例
                const map = new AMap.Map('map-container', {
                    zoom: 13,
                    center: [116.397428, 39.90923], // 默认北京
                    resizeEnable: true
                });
                
                // 添加控件
                map.plugin(['AMap.ToolBar', 'AMap.Scale'], function() {
                    map.addControl(new AMap.ToolBar());
                    map.addControl(new AMap.Scale());
                });
                
                // 获取当前位置
                map.plugin('AMap.Geolocation', function() {
                    const geolocation = new AMap.Geolocation({
                        enableHighAccuracy: true,
                        timeout: 10000,
                        buttonPosition: 'RB',
                        buttonOffset: new AMap.Pixel(10, 20),
                        zoomToAccuracy: true
                    });
                    map.addControl(geolocation);
                    geolocation.getCurrentPosition();
                    
                    AMap.event.addListener(geolocation, 'complete', onLocationComplete);
                    AMap.event.addListener(geolocation, 'error', onLocationError);
                });
                
                // 搜索功能 - 异步实现
                const searchBtn = document.getElementById('map-search-btn');
                const searchInput = document.getElementById('map-search-input');
                
                searchBtn.addEventListener('click', async () => {
                    const keyword = searchInput.value;
                    if (!keyword) return;
                    
                    // 显示加载状态
                    document.getElementById('nearby-list').innerHTML = '<div class="loading">搜索中...</div>';
                    
                    try {
                        // 使用Promise包装高德地图搜索API
                        const searchResult = await new Promise((resolve, reject) => {
                            AMap.plugin('AMap.PlaceSearch', function() {
                                const placeSearch = new AMap.PlaceSearch({
                                    map: map,
                                    pageSize: 10,
                                    pageIndex: 1
                                });
                                
                                placeSearch.search(keyword, function(status, result) {
                                    if (status === 'complete' && result.info === 'OK') {
                                        resolve(result);
                                    } else {
                                        reject(new Error('搜索失败: ' + result.info));
                                    }
                                });
                            });
                        });
                        
                        // 更新列表
                        updateNearbyList(searchResult.poiList.pois);
                    } catch (error) {
                        console.error('搜索错误:', error);
                        document.getElementById('nearby-list').innerHTML = '<div class="no-result">未找到相关地点</div>';
                    }
                });
                
                // 回车键搜索
                searchInput.addEventListener('keypress', (e) => {
                    if (e.key === 'Enter') {
                        searchBtn.click();
                    }
                });
                
                // 筛选功能
                const filterOptions = document.querySelectorAll('.filter-option input');
                filterOptions.forEach(option => {
                    option.addEventListener('change', () => {
                        const selectedTypes = Array.from(filterOptions)
                            .filter(opt => opt.checked)
                            .map(opt => opt.value);
                        
                        // 根据选中的类型筛选地图上的标记点
                        // 这里需要根据实际API调整实现
                        console.log('筛选类型:', selectedTypes);
                    });
                });
                
                // 关闭地点信息面板
                document.getElementById('close-info').addEventListener('click', () => {
                    document.getElementById('place-info').classList.remove('show');
                });
                
                // 导航按钮
                document.getElementById('navigate-btn').addEventListener('click', () => {
                    const placeName = document.getElementById('place-name').textContent;
                    alert(`即将导航到: ${placeName}\n此功能将在下一版本实现`);
                });
                
                // 翻译信息按钮 - 异步实现
                document.getElementById('translate-info-btn').addEventListener('click', async () => {
                    const placeContent = document.getElementById('place-content');
                    const translateBtn = document.getElementById('translate-info-btn');
                    const originalText = placeContent.getAttribute('data-original') || placeContent.textContent;
                    
                    // 如果已经翻译过，切换回原文
                    if (placeContent.getAttribute('data-original')) {
                        placeContent.innerHTML = placeContent.getAttribute('data-original');
                        placeContent.removeAttribute('data-original');
                        translateBtn.innerHTML = '<img src="images/placeholder.svg" alt="翻译" width="16" height="16"> 翻译信息';
                        return;
                    }
                    
                    // 显示加载状态
                    const originalHtml = placeContent.innerHTML;
                    placeContent.innerHTML += '<div class="loading">翻译中...</div>';
                    translateBtn.disabled = true;
                    
                    try {
                        // 调用翻译API
                        const response = await fetch('/api/translate', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify({
                                text: originalText,
                                source_lang: 'zh',
                                target_lang: 'en'
                            }),
                        });
                        
                        const data = await response.json();
                        if (data.error) {
                            throw new Error(data.error);
                        }
                        
                        // 保存原始内容并显示翻译结果
                        placeContent.setAttribute('data-original', originalHtml);
                        placeContent.innerHTML = data.translated_text;
                        translateBtn.innerHTML = '<img src="images/placeholder.svg" alt="原文" width="16" height="16"> 显示原文';
                    } catch (error) {
                        console.error('翻译服务错误:', error);
                        placeContent.innerHTML = originalHtml;
                        alert(`翻译失败: ${error.message}`);
                    } finally {
                        translateBtn.disabled = false;
                    }
                });
                
                return map;
            };
            
            // 位置获取成功回调
            function onLocationComplete(result) {
                // 获取周边兴趣点
                const map = this.getMap();
                const position = result.position;
                
                AMap.plugin('AMap.PlaceSearch', function() {
                    const placeSearch = new AMap.PlaceSearch({
                        type: '风景名胜',
                        pageSize: 10,
                        pageIndex: 1
                    });
                    
                    placeSearch.searchNearBy('', position, 3000, function(status, result) {
                        if (status === 'complete' && result.info === 'OK') {
                            updateNearbyList(result.poiList.pois);
                            
                            // 添加标记
                            result.poiList.pois.forEach(poi => {
                                const marker = new AMap.Marker({
                                    position: poi.location,
                                    title: poi.name,
                                    map: map
                                });
                                
                                // 点击标记显示信息
                                marker.on('click', () => {
                                    showPlaceInfo(poi);
                                });
                            });
                        } else {
                            console.error('获取周边兴趣点失败:', result);
                            document.getElementById('nearby-list').innerHTML = '<div class="no-result">未找到附近景点</div>';
                        }
                    });
                });
            }
            
            // 位置获取失败回调
            function onLocationError(error) {
                console.error('获取位置失败:', error);
                document.getElementById('nearby-list').innerHTML = '<div class="error-msg">获取位置信息失败，请检查位置权限</div>';
            }
            
            // 更新附近地点列表
            function updateNearbyList(pois) {
                const nearbyList = document.getElementById('nearby-list');
                if (!pois || pois.length === 0) {
                    nearbyList.innerHTML = '<div class="no-result">附近没有找到历史文化景点</div>';
                    return;
                }
                
                let html = '';
                pois.forEach(poi => {
                    html += `
                        <div class="nearby-item" data-id="${poi.id}">
                            <h4>${poi.name}</h4>
                            <p>${poi.address || '地址信息不详'}</p>
                            <div class="item-actions">
                                <button class="view-btn" onclick="showPlaceInfo(${JSON.stringify(poi).replace(/\"/g, '&quot;')})">查看详情</button>
                                <span class="distance">${poi.distance ? (poi.distance + 'm') : '距离未知'}</span>
                            </div>
                        </div>
                    `;
                });
                
                nearbyList.innerHTML = html;
            }
            
            // 显示地点详情
            window.showPlaceInfo = function(poi) {
                const placeInfo = document.getElementById('place-info');
                const placeName = document.getElementById('place-name');
                const placeContent = document.getElementById('place-content');
                
                placeName.textContent = poi.name;
                
                // 获取地点的历史文化信息 - 异步实现
                placeContent.innerHTML = `
                    <p><strong>地址:</strong> ${poi.address || '地址信息不详'}</p>
                    <p><strong>电话:</strong> ${poi.tel || '电话信息不详'}</p>
                    <p><strong>类型:</strong> ${poi.type || '类型信息不详'}</p>
                    <div class="loading">加载历史文化信息中...</div>
                `;
                
                (async () => {
                    try {
                        const response = await fetch('/api/culture', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify({
                                query: `关于${poi.name}的历史背景和文化意义`,
                                location: poi.name
                            }),
                        });
                        
                        const data = await response.json();
                        if (data.error) {
                            placeContent.innerHTML = `
                                <p><strong>地址:</strong> ${poi.address || '地址信息不详'}</p>
                                <p><strong>电话:</strong> ${poi.tel || '电话信息不详'}</p>
                                <p><strong>类型:</strong> ${poi.type || '类型信息不详'}</p>
                                <p>暂无历史文化信息</p>
                            `;
                        } else {
                            placeContent.innerHTML = `
                                <p><strong>地址:</strong> ${poi.address || '地址信息不详'}</p>
                                <p><strong>电话:</strong> ${poi.tel || '电话信息不详'}</p>
                                <p><strong>类型:</strong> ${poi.type || '类型信息不详'}</p>
                                <div class="culture-info">
                                    <h4>历史文化背景</h4>
                                    <p>${data.culture_info}</p>
                                </div>
                            `;
                        }
                    } catch (error) {
                        console.error('获取文化信息失败:', error);
                        placeContent.innerHTML = `
                            <p><strong>地址:</strong> ${poi.address || '地址信息不详'}</p>
                            <p><strong>电话:</strong> ${poi.tel || '电话信息不详'}</p>
                            <p><strong>类型:</strong> ${poi.type || '类型信息不详'}</p>
                            <p class="error-msg">获取历史文化信息失败</p>
                        `;
                    }
                })();
                
                placeInfo.classList.add('show');
            };
            
            // 初始化
            initMap();
        });
    </script>
</body>
</html>